/*
Copyright 2022 The Karmada Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
)

// MarkdownPostProcessing goes through the generated files
func MarkdownPostProcessing(cmd *cobra.Command, dir string, processor func(string) string) error {
	for _, c := range cmd.Commands() {
		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
			continue
		}
		if err := MarkdownPostProcessing(c, dir, processor); err != nil {
			return err
		}
	}

	basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
	filename := filepath.Join(dir, basename)

	// Remove the markdown file for the version subcommand
	if strings.Contains(basename, "version") {
		return os.Remove(filename)
	}

	markdownBytes, err := os.ReadFile(filename)
	if err != nil {
		return err
	}

	processedMarkDown := processor(string(markdownBytes))

	return os.WriteFile(filename, []byte(processedMarkDown), 0600)
}

// cleanupForInclude parts of markdown that will make difficult to use it as include in the website:
// - The section before synopsis.
// - The sections see also.
func cleanupForInclude(md string) string {
	lines := strings.Split(md, "\n")

	// add title for component docs
	firstL := lines[0]
	title := strings.TrimPrefix(firstL, "## ")
	lines[0] = "---"
	newlines := []string{"---", "title: " + title}
	newlines = append(newlines, lines...)

	cleanMd := ""
	for i, line := range newlines {
		if line == "### SEE ALSO" {
			break
		}

		cleanMd += line
		if i < len(newlines)-1 {
			cleanMd += "\n"
		}
	}

	cleanMd += "###### Auto generated by [spf13/cobra script in Karmada](https://github.com/karmada-io/karmada/tree/master/hack/tools/gencomponentdocs)"
	return cleanMd
}
